#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

int search_file(const char *filename, const char *pattern);
int search_directory(const char *dirname, const char *pattern);

int main(int argc, char *argv[])
{
    int recursive = 0;
    int i;
    for (i = 1; i < argc; i++)
    {
         if (strcmp(argv[i], "-r") == 0)
         {
               recursive = 1;
          }
          else
          {
              break;
          }
     }
     if(recursive)
     {
         search_directory(argv[i+1], argv[i]);
     }
     else
     {
         search_file(argv[i+1], argv[i]);
     }
     return 0;
}

int search_file(const char *filename, const char *pattern)
{
    FILE *file = fopen(filename, "r");
    if (file == NULL)
    {
        return 1;
    }
    char buffer[1024];
    while (fgets(buffer, sizeof(buffer), file) != NULL) 
    {
        if (strstr(buffer, pattern) != NULL)
        {
            printf("%s", buffer);
        }
    }
    fclose(file);
    return 0;
}

int search_directory(const char *dirname, const char *pattern)
{
    DIR *dir = opendir(dirname);
    if (dir == NULL)
    {
        return -1;
    }
    struct dirent *entry;
    struct stat statbuf;
    while ((entry = readdir(dir)) != NULL) 
    {
        char path[1024];
        snprintf(path, sizeof(path), "%s/%s", dirname, entry->d_name);
        if (stat(path, &statbuf) == -1) continue;
        if (S_ISDIR(statbuf.st_mode))
        {
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;
            search_directory(path, pattern);
        }
        else
        {
            search_file(path, pattern);
        }
     }
     closedir(dir);
     return 0;
}



